package com.newland.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 *Description:
 *Version:1.0.0
 *@author shihb
 *@date 2020/3/30 15:27
 */
public class DBUtils {
  private static String  driver,url,user,pwd;
  private static Connection conn =null;
  private static ResultSet rs = null;
  private static Statement sta = null;

  static {
    try {
      Properties prop=MyUtils.getConfig();
      driver = prop.getProperty("oracleDriver");
      url = prop.getProperty("oracleUrl");
      user = prop.getProperty("oracleUser");
      pwd = prop.getProperty("oraclePwd");
      Class.forName(driver);
    } catch (Exception e){
      throw new RuntimeException("driver load fail",e);
    }
  }
  /**
   * @return 连接对象
   */
  public static Connection getConn() throws SQLException{
    if(conn==null){
      conn=DriverManager.getConnection(url, user, pwd);
    }
    return conn;
  }

  /**
   * 这个业务简单就不单独写dao层了
   * @param sql
   * @return
   */
  public static ResultSet executeSql(String sql) {
    try {
      getConn();
      sta = conn.createStatement();
      // 得到结果集
      rs = sta.executeQuery(sql);
    } catch (Exception e) {
      System.out.println("executeSql error sql:"+sql);
      e.printStackTrace();
    }
    return  rs;
  }
  public static void batchExecuteSql(List<String> sqlList) {
    try {
      getConn();
      sta = conn.createStatement();
      for(String sql:sqlList){
        sta.addBatch(sql);
      }
      sta.executeBatch();
    } catch (Exception e) {
      System.out.println("executeSql error sql:"+sqlList);
      e.printStackTrace();
    }
  }
  /**
   * 关闭资源
   */
  public static void close(Connection conn,Statement sta,ResultSet rs) {
    try {
      if (rs != null) {
        rs.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (sta != null) {
          ;        sta.close();
        }
      } catch (SQLException e2) {
        e2.printStackTrace();
      } finally {
        if (conn != null) {
          try {
            conn.close();
          } catch (SQLException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
  public static void close() {
    try {
      if (rs != null) {
        rs.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (sta != null) {
          ;        sta.close();
        }
      } catch (SQLException e2) {
        e2.printStackTrace();
      } finally {
        if (conn != null) {
          try {
            conn.close();
          } catch (SQLException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

}
